package com.vhdadw.strategy;

import com.vhdadw.enums.BizCodeEnum;
import com.vhdadw.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     *
     * @param availableTargetNames 数据源集合
     *                             在分库是值为所有分片库的集合 databaseNames
     *                             在分表是值为所有分片表的集合 tableNames
     * @param shardingValue 分片属性,包括
     *                      logicColumnName 逻辑分片列名称
     *                      columnName 实际分片列名称
     *                      value 分片列的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {

        // 获取短链码第一位，即库位
        String codePrefix = shardingValue.getValue().substring(0,1);

        for(String targetName : availableTargetNames){
            // 获取库名最后一位 ds0,ds1,dsa
            String targetNameSuffix = targetName.substring(targetName.length() - 1);

            //一致则返回
            if(codePrefix.equals(targetNameSuffix)){
                return targetName;
            }
        }
        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);
    }
}
